package collection.map;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author weim
 * @date 18-8-27
 *
 *
 * 可以排序  默认key字典升序
 *
 * 通过红黑树实现的
 *
 * 非线程安全
 *
 */
public class MyTreeMap {

    public static void main(String[] args) {

        TreeMap<String, String> map = new TreeMap<String, String>();
        map.put("a","avalue");
        map.put("e","evalue");
        map.put("b","bvalue");
        map.put("f","fvalue");
        map.put("d","dvalue");
        map.put("c","cvalue");
        //key不能为null
//        map.put(null, null);
        map.put("", null);

        System.out.println(map.toString());

        TreeMap<String, String> map2 = new TreeMap<String, String>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2) * -1;
            }
        });

        map2.put("a","avalue");
        map2.put("e","evalue");
        map2.put("b","bvalue");
        map2.put("f","fvalue");
        map2.put("d","dvalue");
        map2.put("c","cvalue");

        System.out.println(map2.toString());

        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
            //快速失败  在iterator遍历的时候，更改map结构，会抛出ConcurrentModificationException异常
//            map.put("g","gvalue");
        }
    }
}
